package repository

import (
	"errors"
	"fmt"
	"gitee.com/ling1314/origin-utility/db"
	"gitee.com/ling1314/origin-utility/model"
)

type appRepository struct{}

// FindIssueList 根据应用名称或者别名查询应用列表
func (r appRepository) FindIssueList(str string) (li []model.AppIssue, err error) {
	err = db.GetDB().Model(&model.AppIssue{}).Where("app_name like ? or alias like ?", fmt.Sprintf("%%%s%%", str),
		fmt.Sprintf("%%%s%%", str)).Find(&li).Error
	return
}

func (r appRepository) DeleteAppInstallByHostId(hostId int64) (err error) {
	err = db.GetDB().Where("host_id = ? ", hostId).Delete(&model.AppInstall{}).Error
	return
}

func (r appRepository) BatchInsertAppInstallList(li []model.AppInstall) error {
	return db.GetDB().Create(&li).Error
}

func (r appRepository) FindById(appId int64) (u model.AppInstall, err error) {
	err = db.GetDB().Where("id=?", appId).Find(&u).Error
	return
}

func (r appRepository) UpdateById(u *model.AppInstall) (err error) {
	return db.GetDB().Save(&u).Error
}
func (r appRepository) FindPage(page model.PageInfo, name string) (results []model.AppInstall, total int64, err error) {
	err = db.GetDB().Model(&model.AppInstall{}).
		Where(" name like ? ", "%"+name+"%").Find(&results).
		Limit(page.PageSize).Offset((page.Page - 1) * page.PageSize).Count(&total).Error
	return
}

func (r appRepository) FindListWithClusterId(clusterId int64) (li []model.AppIssue, err error) {
	err = db.GetDB().Model(&model.AppIssue{}).Where("cluster_id = ?", clusterId).Find(&li).Error
	return
}

func (r appRepository) IsExist(exePath, workSpace, appParams string, hostId int64) bool {
	var (
		err error
		t   int64
	)
	err = db.GetDB().Where("exe_path = ? and work_space =? and app_params=? and host_id", exePath, workSpace, appParams).Count(&t).Error
	if err != nil {
		return false
	}
	return t > 0
}

func (r appRepository) FindAppInstallListByClusterId(clusterId int64) (li []model.AppInstall, err error) {
	err = db.GetDB().Raw("SELECT  * FROM  va_app_install  WHERE host_id in ("+
		" select host_id from va_host WHERE cluster_id =? "+
		") GROUP BY exe_path,work_space,app_params", clusterId).Scan(&li).Error
	return
}

func (r appRepository) FindAppInstallListByIds(ids []int64) (li []model.AppInstall, err error) {
	err = db.GetDB().Model(&model.AppInstall{}).Where("id in ?", ids).Find(&li).Error
	return
}

func (r appRepository) FindAppInstallById(id int64) (m model.AppInstall, err error) {
	err = db.GetDB().Model(&model.AppInstall{}).Where("id=?", id).Find(&m).Error
	return
}

// CheckIssueStatus 检查应用是否已经发布过，只考虑 执行文件路径、参数、工作空间. false-未安装过  true-安装过
func (r appRepository) CheckIssueStatus(exePath, workSpace, appParams string, clusterId int64) (m model.AppIssue, b bool, err error) {
	var (
		t int64
	)
	err = db.GetDB().Model(&model.AppIssue{}).Where("exec_path =? and work_space =? and app_params =? and cluster_id =?",
		exePath, workSpace, appParams, clusterId).Find(&m).Count(&t).Error
	if err != nil {
		return m, false, err
	}
	return m, t > 0, nil
}

// CheckIssueStatusForAll 检查应用是否已经发布过，只考虑 执行文件路径、参数、工作空间. false-未安装过  true-安装过
func (r appRepository) CheckIssueStatusForAll(exePath, workSpace, appParams string, displayMode int, isAdmin bool, clusterId int64) (m model.AppIssue, b bool, err error) {
	var (
		t int64
	)
	err = db.GetDB().Model(&model.AppIssue{}).Where("exec_path =? and work_space =? and app_params =? "+
		" and cluster_id =? and display_mode =? and is_admin =?", displayMode, isAdmin,
		exePath, workSpace, appParams, clusterId).Find(&m).Count(&t).Error
	if err != nil {
		return m, false, err
	}
	return m, t > 0, nil
}

func (r appRepository) InsertAppIssue(m *model.AppIssue) (err error) {
	return db.GetDB().Save(&m).Error
}

func (r appRepository) FindAppIssueById(id int64) (m model.AppIssue, err error) {
	err = db.GetDB().Model(&model.AppIssue{}).Where("app_id = ?", id).Find(&m).Error
	return
}

func (r appRepository) UpdateAppIssue(m *model.AppIssue) (err error) {
	var dm *model.AppIssue
	if db.GetDB().Model(&model.AppInstall{}).Where("app_id =?", m.AppId).First(&dm).Error != nil {
		return errors.New("id not exist")
	}
	err = db.GetDB().Save(&m).Error
	return
}

func (r appRepository) FindMapDeptAppForDeptIds(appId int64) (li []int64, err error) {
	err = db.GetDB().Raw("SELECT dept_id FROM va_map_dept_app WHERE app_id = ? ", appId).Find(&li).Error
	return
}

func (r appRepository) FindMapDirectAppForUserIds(appId int64) (li []int64, err error) {
	err = db.GetDB().Raw("SELECT user_id FROM va_map_direct_app  WHERE app_id = ? ", appId).Find(&li).Error
	return
}

func (r appRepository) DeleteMapDeptAppForAppId(appId int64) (err error) {
	err = db.GetDB().Exec("DELETE FROM va_map_dept_app WHERE app_id = ? ", appId).Error
	return
}

func (r appRepository) DeleteMapDirectAppForAppId(appId int64) (err error) {
	err = db.GetDB().Exec("DELETE FROM va_map_direct_app WHERE app_id = ? ", appId).Error
	return
}

func (r appRepository) InsertMapDeptApp(appId int64, deptIds []int64) error {
	if len(deptIds) == 0 {
		return nil
	}
	li := make([]model.MapDeptApp, len(deptIds))
	for i, v := range deptIds {
		li[i] = model.MapDeptApp{
			DeptId: v,
			AppId:  appId,
		}
	}
	err := db.GetDB().Model(&model.MapDeptApp{}).CreateInBatches(li, len(li)).Error
	return err
}

func (r appRepository) InsertMapDirectApp(appId int64, uIds []int64) error {
	if len(uIds) == 0 {
		return nil
	}
	li := make([]model.MapDirectApp, len(uIds))
	for i, v := range uIds {
		li[i] = model.MapDirectApp{
			UserId: v,
			AppId:  appId,
		}
	}
	err := db.GetDB().Model(&model.MapDirectApp{}).CreateInBatches(li, len(li)).Error
	return err
}

func (r appRepository) FindGlobalApps() (li []model.AppIssue, err error) {
	err = db.GetDB().Model(&model.AppIssue{}).Where("is_public = true ").Find(&li).Error
	return
}

// FindIssueApps 根据应用ID查询应用列表
func (r appRepository) FindIssueApps(ids []int64) (li []model.AppIssue, err error) {
	err = db.GetDB().Model(&model.AppIssue{}).Where("app_id in ?", ids).Find(&li).Error
	return
}

// FindDeptAppIds 查询部门应用列表id
func (r appRepository) FindDeptAppIds(depId int64) (li []int64, err error) {
	err = db.GetDB().Raw("select app_id from va_map_dept_app WHERE dept_id = ?", depId).Find(&li).Error
	return
}

// FindUserAppIds 查询用户私有应用列表id
func (r appRepository) FindUserAppIds(userId int64) (li []int64, err error) {
	err = db.GetDB().Raw("select app_id from va_map_direct_app WHERE user_id = ?", userId).Find(&li).Error
	return
}

func (r appRepository) DeleteIssueApp(appId int64) (err error) {
	err = db.GetDB().Where("app_id = ?", appId).Delete(&model.AppIssue{}).Error
	return
}
